//1,新建文件   /pages/home/index.dart

//2,添加 material, page_content 依赖
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutterapp/page/utils/common_toast.dart';
import 'package:flutterapp/page/utils/dio_http.dart';
import 'package:flutterapp/page/utils/scopoed_model_helper.dart';
import 'package:flutterapp/page/utils/store.dart';
import 'package:flutterapp/page/utils/string_is_null_or_entity.dart';
import 'package:flutterapp/scoped_model/auth.dart';

//3, 编写无状态组件

//有状态组件
class LoginPage extends StatefulWidget {
  //构造函数
  const LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool showPassword = false;

  var usernameController = TextEditingController();
  var passwordController = TextEditingController();

  _loginHandle() async {
    print('点击了登录');
    var username = usernameController.text;
    var password = passwordController.text;
    if (stringIsNullOrEmpty(username) || stringIsNullOrEmpty(password)) {
      CommonToast.showToast('用户名或者密码不能为空');
      return;
    }

    const url = '/api/user/login';
    var params = {'username': username, 'pass': password};
    //1,发送请求 连接超时5秒
    var res = await DioHttp.of(context).post(url, params);

    //2,获取参数 json.decode 类似php转json语法
    var resMap = json.decode(res.toString());
    bool dflag = resMap['flag'];
    String message = resMap['message'] ?? '内部错误';
    print(dflag);

    //判断返回开头是否是2开头的
    // if(dflag.toString().startsWith('2')){

    // }
    if (dflag) {
      print('进来了---------------------------------存token');

      // resMap['data']['token']; 第二层
      String token = resMap['token'].toString();
      print('token-----------------------');
      print(token);
      Store store = await Store.getInstance();
      //设置token
      await store.setString(StoreKeys.token, token);

      //更新状态 把tokne 写入到全局model
      ScopedModelHelper.getModel<AuthModel>(context).login(token, context);

      //延迟一秒
      Timer(Duration(seconds: 1), () {
        //回到上一个页面
        Navigator.of(context).pop();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // 1,添加 Scaffaid

    //2,完成appBar 部分

    //3,完成body 部分

    //3.1 用户名

    //3.2密码

    //3.3登录按钮

    //3.4注册按钮

    //4.主体颜色
    //

    //5 测试
    return Scaffold(
      appBar: AppBar(
        centerTitle: true, // 标题居中
        title: Text("登录"),
      ),
      body: SafeArea(
        minimum: EdgeInsets.all(30),
        child: ListView(
          children: [
            TextField(
              controller: usernameController,
              decoration: InputDecoration(labelText: '用户名', hintText: '请输入用户名'),
            ),
            Padding(
              padding: EdgeInsets.all(10),
            ),
            TextField(
              controller: passwordController,
              obscureText: !showPassword,
              decoration: InputDecoration(
                labelText: '密码',
                hintText: '请输入密码',
                suffixIcon: IconButton(
                  icon: Icon(
                    showPassword ? Icons.visibility_off : Icons.visibility,
                  ),
                  onPressed: () {
                    setState(() {
                      showPassword = !showPassword;
                    });
                  },
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(10),
            ),
            RaisedButton(
              color: Colors.green,
              child: Text('登录', style: TextStyle(color: Colors.white)),
              onPressed: () {
                // 点击逻辑
                _loginHandle();
              },
            ),
            Padding(
              padding: EdgeInsets.all(10),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text('还没有账号,注册新用户'),
                FlatButton(
                    onPressed: () {
                      Navigator.pushReplacementNamed(context, 'register');
                    },
                    child: Text(
                      '去注册',
                      style: TextStyle(color: Colors.green),
                    ))
              ],
            )
          ],
        ),
      ),
    );
  }
}

//4,使用PageContent
